package acs.http;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import acs.offer.collection.Params;
import acs.offer.constant.Constant;
import acs.offer.constant.EventType;
import acs.offer.util.ServerCache;

/**
 * 针对于一个请求URL，包含了请求类型和参数
 * @author Administrator
 *
 */
public class DmsTask {
	List<Params> paramsList=new ArrayList<>();
	private static final int STATE_INIT = 1;
	private static final int STATE_WAITING_DATA = 2;// 加载数据中
//	private static final int STATE_TIME_OUT = 3;
	private static final int STATE_DATA_LOADED = 4;
	private int currentState = STATE_INIT;// 状态
	private int timeOutCount = 0;// 超时的次数
	private long requestTime = 0;// 处理新请求的时间戳
	private Map<String, String> resultDatas ;//结果
	/**
	 * 获取数据
	 * @param param
	 */
	public void loadData(Params params) {
		this.setRequestTime(System.currentTimeMillis());//说明被请求了
		switch (currentState) {
		case STATE_INIT://可以加载数据
			synchronized (this) {//避免并发问题
				this.currentState=STATE_WAITING_DATA;
				String sessionId=params.get(Constant.SESSION_ID);
				DMSSoftTimer.getInstance().startTimer(sessionId,Constant.MAX_WAIT_DATA_TIME, EventType.TIMEOUT_FOR_LOAD_DATA,params);//开始清除缓存倒计时
				String cacheKey = params.get(Constant.REQUEST_URI);
				resultDatas = ServerCache.getInstance().get(cacheKey);
				if(resultDatas == null) {
					CompletableFuture.runAsync(()->{
						 loadDbData(params);
					});
				}else {
					this.currentState=STATE_DATA_LOADED;
					loadData(params) ;
				}
			}
			break;
		case STATE_WAITING_DATA:
			this.addParam(params);
			break;
		case STATE_DATA_LOADED:
			this.addParam(params);
			this.notifyInstance();
			break;
		}
		
	}
	/**
	 * 响应客户端
	 */
	private void notifyInstance() {
		System.out.println("服务端查到了datas，现在开始给客户端返回datas:"+this.resultDatas);
		Iterator<Params> iterator = paramsList.iterator();
		while(iterator.hasNext()) {
			Params params = iterator.next();
			iterator.remove();
			params.put(Constant.RESPONSE_DATA, resultDatas);
			HttpServerHandler.sendMessage(params);
		}
	}
	/**
	 * 去数据库加载数据，是一个比较耗时的操作
	 * @param requestType
	 * @param param
	 * @param params
	 * @return
	 */
	private Map<String, String> loadDbData(Params params){
//		try {
//			Thread.sleep(2 * 1000);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
		System.out.println("根据参数去数据库加载数据");
		resultDatas=new HashMap<>();
		String requestType=params.get(Constant.REQUEST_TYPE);
		Map<String, Object> param=params.get(Constant.REQUEST_PARAMS);
		for(Map.Entry<String,Object> entry : param.entrySet()) {
			resultDatas.put(requestType+":"+entry.getKey(), entry.getValue().toString());
		}
		
		String cacheKey=params.get(Constant.REQUEST_URI);
		ServerCache.getInstance().put(cacheKey,resultDatas);//加入缓存
		this.currentState=STATE_DATA_LOADED;//当前状态改成已加载完数据
		String sessionId=params.get(Constant.SESSION_ID);
		DMSSoftTimer.getInstance().cancel(EventType.TIMEOUT_FOR_LOAD_DATA, sessionId);
		this.loadData(params);
		return resultDatas;
	}

	public List<Params> getParamsList() {
		return paramsList;
	}
	public void setParamsList(List<Params> paramsList) {
		this.paramsList = paramsList;
	}
	
	public int timeOut() {
		return ++timeOutCount;
	}
	public long getRequestTime() {
		return requestTime;
	}
	public void setRequestTime(long requestTime) {
		this.requestTime = requestTime;
	}
	
	private void addParam(Params param) {
		String sessionId = param.get(Constant.SESSION_ID);
		for (Params p : paramsList) {
			if(sessionId.equals(p.get(Constant.SESSION_ID))) {
				return ;
			}
		}
		paramsList.add(param);
	}
	
	public static void main(String[] args) {
		List<Params> list=new ArrayList<>();
		Params param = Params.build();
		list.add(param);
		list.add(param);
		list.add(param);
		System.out.println(list);
	}
	
}
